package com.woniuxy.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HP
 * @version 1.0
 * @project
 * @description
 * @date 2024/3/15 17:24:42
 */
public class JWTUtil {

    private static final String key = "SHAJKHDSJKAHDSJKAHDJKSAHDJKSAHDJKSAHDJKSAHDJKDJHSAJ" +
            "HJKSDAHJKDHSJKAHDJKSAHDJKSA" +
            "HDJKSAHDJKSAHDJKSAHDJKSAHKJD" +
            "KDHSAJKHDSJKAHDJKSAHDJKSAHJDK";
    //生成jwt的方法
    public static String createJWT(Map map) throws JOSEException {
        JWSHeader build = new JWSHeader.Builder(JWSAlgorithm.HS256)
                .type(JOSEObjectType.JWT)
                .build();
        Payload payload = new Payload(new HashMap<>(map));


        //生成签名
        //签名算法  1.头部  2.载荷  3.密钥
        JWSObject jwsObject = new JWSObject(build, payload);
        String key = "SHAJKHDSJKAHDSJKAHDJKSAHDJKSAHDJKSAHDJKSAHDJKDJHSAJ" +
                "HJKSDAHJKDHSJKAHDJKSAHDJKSA" +
                "HDJKSAHDJKSAHDJKSAHDJKSAHKJD" +
                "KDHSAJKHDSJKAHDJKSAHDJKSAHJDK";
        MACSigner macSigner = new MACSigner(key);//添加密钥
        jwsObject.sign(macSigner); //利用密钥加密的方法
        return jwsObject.serialize(); //把生成好的jwt对象序列化为字符串
    }

    //用系统jwt的密钥去解析jwt
    public static Boolean decode(String jwt) throws ParseException, JOSEException {
        JWSObject jwtObj = JWSObject.parse(jwt);
        MACVerifier macVerifier = new MACVerifier(key);
        return jwtObj.verify(macVerifier);//解密
    }


    //获取jwt中的用户信息,
    //jwt中的字符串是 jwt 对象序列化来的
    // 反序列化:字符串转成对象
    public  static Map getUserInfo( String jwt) throws ParseException {
        //反序列化jwt字符串
        JWSObject jwtObj = JWSObject.parse(jwt);
        Payload payload = jwtObj.getPayload();
        return payload.toJSONObject(); //载荷中的用户信息
    }




















}
